<?php
namespace Admin\Controller;

use Think\Controller;
use Think\Page;

class WeixinController extends Controller{
    // 粉丝用户列表
    public function userList(){
        $fans_M = M('wechat_fans');
        
        // 实现分页
        $count = $fans_M->count();
        
        $page = new Page($count,10);
        
        // 获取粉丝数据
        $fans = $fans_M->limit($page->firstRow,$page->listRows)->select();
        
        $this->assign('fans',$fans);
        $this->assign('count',$count);
        $this->assign('show',$page->show());
        
        $this->display();
    }
    
    // 显示二维码
    public function code(){
        
        // 获取标签id
        $tag_id = I('get.tag_id');
        
        // 获取过期时间
        $fans_tag = M('fans_tags')->where(array('id'=>$tag_id))->field('time,code,id')->find();
        if($fans_tag['time'] == -1){ // 永久的二维码
            $code = $fans_tag['code'];
        }else { //临时的二维码
            $time = time() - $fans_tag['time'] - 6*24*3600;
            if($time > 0){ // 过期
                
                // 重新创建二维码
                $accessToken = getAccessToken();
                $url = 'https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token='.$accessToken;
                $date = 7*24*3600;
                $data = '{"expire_seconds": '.$date.', "action_name": "QR_SCENE", "action_info": {"scene": {"scene_id": 99'.$fans_tag['id'].'}}}';
                $res = https_request($url,$data);
                $info = json_decode($res,true);
                
                if(!empty($info['ticket'])){
                    $url = 'https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket='.urlencode($info['ticket']);
                    if(!file_exists('Public/code')){
                        mkdir('Public/code');
                    }
                    
                    $res = https_request($url);
                    $path = 'Public/code/'.time().'.jpg';
                    file_put_contents($path, $res);

                    // 保存到数据库
                    $fans_data = array(
                        'code' => '/'.$path,
                        'time' => time()
                    );
                    M('fans_tags')->where(array('id'=>$tag_id))->save($fans_data);
                    $code = '/'.$path;
                }
                
            }else { // 未过期
                $code = $fans_tag['code'];
            }
        }
        
        $this->assign('code',$code);
        
        $this->display();
    }
    
    // 修改粉丝备注
    public function changeRemark(){
        
        // 获取备注值跟openid
        $openid = I('post.openid');
        $remark = I('post.remark');
        
        // 修改微信远程数据
        // 获取accessToken
        $accessToken = getAccessToken();
        $url = 'https://api.weixin.qq.com/cgi-bin/user/info/updateremark?access_token='.$accessToken;
        $data = '{"openid":"'.$openid.'","remark":"'.$remark.'"}';
        $res = https_request($url,$data);
        $info = json_decode($res,true);
        if($info['errcode'] == 0){ // 修改成功
            
            // 修改后台数据库数据
            $res = M('wechat_fans')->where(array('openid'=>$openid))->setField('remark',$remark);
            
            if ($res){
                $this->ajaxReturn(array('status'=>1,'msg'=>'修改备注成功'));
            }
        }
        
        $this->ajaxReturn(array('status'=>0,'msg'=>'修改备注失败，请稍后重试'));
    }
    
    // 设置粉丝标签
    public function setTag(){
        // 获取accessToken
        $accessToken = getAccessToken();
        if(IS_POST){
            // 获取粉丝id
            $openid = I('post.openid');
            
            // 获取粉丝标签
            $tag = M('wechat_fans')->where(array('openid'=>$openid))->getField('tagid_list');
            
            if (!empty($tag)){ // 移除原来的标签
                $url = 'https://api.weixin.qq.com/cgi-bin/tags/members/batchuntagging?access_token='.$accessToken;
                $tag_s = explode(',', $tag);
                foreach ($tag_s as $v){
                    $data = '{"openid_list" : ["'.$openid.'"],"tagid" : '.$v.'}';
                    https_request($url,$data);
                }
            }
            
            // 添加新的标签
            $tags = I('post.tags');
            
            if(!empty($tags)){
                $url = 'https://api.weixin.qq.com/cgi-bin/tags/members/batchtagging?access_token='.$accessToken;
                $count = 0;
                foreach ($tags as $v){
                    $data = '{"openid_list" : ["'.$openid.'"],"tagid" : '.$v.'}';
                    $res = https_request($url,$data);
                    $info = json_decode($res,true);
                    if ($info['errcode'] == 0){
                        $count++;
                    }
                }
                if($count != count($tags)){
                    $this->ajaxReturn(array('status'=>0,'msg'=>'修改标签失败，请稍后重试'));
                }
            }
            // 修改数据库数据
            $tagid_list = implode(',', $tags);
            $res = M('wechat_fans')->where(array('openid'=>$openid))->setField('tagid_list',$tagid_list);
            
            if ($res !== false){
                $this->ajaxReturn(array('status'=>1,'msg'=>'修改标签成功'));
            }else {
                $this->ajaxReturn(array('status'=>0,'msg'=>'修改标签失败，请稍后重试'));
            }
           
        }else {
            
            // 获取粉丝id
            $openid = I('get.openid');
            
            // 获取粉丝标签
            $tag = M('wechat_fans')->where(array('openid'=>$openid))->getField('tagid_list');
            $fans_tag = explode(',', $tag);
            
            // 获取标签列表
            $tags = M('fans_tags')->field('name,id')->select();
            
            $this->assign('openid',$openid);
            $this->assign('tags',$tags);
            $this->assign('fans_tag',$fans_tag);
            $this->display();
        }
    }
    
    // 粉丝标签列表
    public function tagList(){
        $fans_tags= M('fans_tags');
        
        $tags = $fans_tags->select();
        
        $this->assign('tags',$tags);
        
        $this->display();
    }
    
    // 添加标签
    public function tagsAdd(){
        if(IS_POST){
            $name = I('post.name');
            
            // 获取accessToken
            $accessToken = getAccessToken();
            
            $fansTag_M = M('fans_tags');
            
            if(I('post.tag_id') > 0){ // 修改数据
                $data = I('post.');
                $url = 'https://api.weixin.qq.com/cgi-bin/tags/update?access_token='.$accessToken;
                
                $res = https_request($url,'{"tag":{"id":"'.$data['tag_id'].'","name":"'.$data['name'].'"}}');
                $info = json_decode($res,true);
                if ($info['errcode'] == 0){
                    $data['id'] = $data['tag_id'];
                    unset($data['tag_id']);
                    // 添加数据
                    $res = $fansTag_M->save($data);
                    if ($res){
                        $this->ajaxReturn(array('status'=>1,'msg'=>'修改标签成功'));
                    }
                    
                }
            }else { // 添加数据
                $url = 'https://api.weixin.qq.com/cgi-bin/tags/create?access_token='.$accessToken;
                
                $res = https_request($url,'{"tag":{"name":"'.$name.'"}}');
                $info = json_decode($res,true);
                if ($info['tag']['id'] > 0){
                    
                    // 添加数据
                    $res = $fansTag_M->add($info['tag']);
                    if ($res){
                        $this->ajaxReturn(array('status'=>1,'msg'=>'添加标签成功'));
                    }
                    
                }
            }
            
            $this->ajaxReturn(array('status'=>0,'msg'=>'添加标签失败，请稍后重试'));
        }elseif(I('get.tag_id') > 0){
            
            // 获取标签信息
            $tag = M('fans_tags')->where(array('id'=>I('get.tag_id')))->find();
            
            $this->assign('tag',$tag);
            $this->display();
        }else {
            $this->display();
        }
    }
    
    // 删除标签
    public function tagDel(){
        
        // 获取标签id
        $tag_id = I('get.tag_id');
        
        $accessToken = getAccessToken();
        
        $url = 'https://api.weixin.qq.com/cgi-bin/tags/delete?access_token='.$accessToken;
        $data = '{"tag":{"id":'.$tag_id.'}}';
        $res = https_request($url,$data);
        $info = json_decode($res,true);
        
        if ($info['errcode'] == 0){ // 删除成功
            
            // 删除数据库数据
            $res = M('fans_tags')->delete($tag_id);
            
            if ($res){
                $this->ajaxReturn(array('status'=>1,'msg'=>'删除成功'));
            }
        }
        $this->ajaxReturn(array('status'=>0,'msg'=>'标签删除失败，请稍后再试'));
    }
    
    // 同步标签列表数据
    public function refreshTagData(){
        $refreshData = cookie('refreshTagData');
        if (!empty($refreshData)){
            $this->ajaxReturn(array('status'=>0,'msg'=>'30分钟内只能刷新一次'));
        }
        // 获取accessToken
        $accessToken = getAccessToken();
        
        // 设置请求地址
        $url = 'https://api.weixin.qq.com/cgi-bin/tags/get?access_token='.$accessToken;
        
        // 获取用户的openid
        $res = https_request($url);
        $info = json_decode($res,true);
        $tags= $info['tags'];
        
        $fans_tags= M('fans_tags');
        
        // 通过openid来获取用户的基本信息
        $users = array();
        foreach ($tags as $v){
            
            $name = $fans_tags->where(array('id'=>$v['id']))->getField('name');
            if (!empty($name)){ // 修改数据
                $res = $fans_tags->where(array('id'=>$v['id']))->save($v);
            }else { // 添加数据
                $res = $fans_tags->add($v);
            }
            if($res === false){
                $this->ajaxReturn(array('status'=>0,'msg'=>'数据同步失败，请刷新后重试'));
            }
        }
        cookie('refreshTagData',1,1800);
        $this->ajaxReturn(array('status'=>1,'msg'=>'同步成功'));
    }
    
    // 同步粉丝列表数据
    public function refreshData(){
        $refreshData = cookie('refreshData');
        if (!empty($refreshData)){
            $this->ajaxReturn(array('status'=>0,'msg'=>'30分钟内只能刷新一次'));
        }
        // 获取accessToken
        $accessToken = getAccessToken();
        
        // 设置请求地址
        $url = 'https://api.weixin.qq.com/cgi-bin/user/get?access_token='.$accessToken;
        
        // 获取用户的openid
        $res = https_request($url);
        $info = json_decode($res,true);
        $openid= $info['data']['openid'];
        
        $wechatFans_M = M('wechat_fans');
        
        // 通过openid来获取用户的基本信息
        $users = array();
        foreach ($openid as $v){
            $url = 'https://api.weixin.qq.com/cgi-bin/user/info?access_token='.$accessToken.'&openid='.$v.'&lang=zh_CN';
            $res = https_request($url);
            $info = json_decode($res,true);
            unset($info['subscribe']);
            unset($info['groupid']);
            $info['tagid_list'] = implode(',', $info['tagid_list']);
            $users[] = $info;
            
            $id = $wechatFans_M->where(array('openid'=>$info['openid']))->getField('id');
            if ($id > 0){ // 修改数据
                $res = $wechatFans_M->where(array('id'=>$id))->save($info);
            }else { // 添加数据
                $res = $wechatFans_M->add($info);
            }
            if($res === false){
                $this->ajaxReturn(array('status'=>0,'msg'=>'数据同步失败，请刷新后重试'));
            }
        }
        cookie('refreshData',1,1800);
        $this->ajaxReturn(array('status'=>1,'msg'=>'同步成功'));
    }

    
}